package com.ruoyi.basebill.service.impl;

import com.ruoyi.basebill.domain.*;
import com.ruoyi.basebill.service.IJszxApiService;
import com.ruoyi.basebill.util.OmsUtil;
import com.ruoyi.basedata.domain.*;
import com.ruoyi.basedata.service.IBdMaterialService;
import com.ruoyi.basedata.service.IBdWarehouseService;
import com.ruoyi.basedata.service.impl.BdWarehouseServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @projectName: wfz
 * @package: com.ruoyi.basebill.service.impl
 * @className: IJszxApiServiceImpl
 * @author: Eric
 * @description: TODO
 * @date: 2023/3/7 15:58
 * @version: 1.0
 */
@Service
public class JszxApiServiceImpl implements IJszxApiService {

    @Autowired
    private OmsUtil omsUtil;

    @Autowired
    private BdWarehouseServiceImpl warehouseService;

    @Autowired
    private IBdWarehouseService bdWarehouseService;

    @Autowired
    private IBdMaterialService bdMaterialService;

    @Override
    public OmsTransferbill getTransferBill(OmsTransferbill omsTransferbill) {
        String fromshopid = omsTransferbill.getFromshopid();//调出门店（客户）
        String toshopid = omsTransferbill.getToshopid();//调入门店编码
        List<OmsTransferbillentry> omsTransferbillentryList = omsTransferbill.getOmsTransferbillentryList();

        BdCustomer fromcustomer = omsUtil.getCustomer(fromshopid); //调出客户
        BdCustomer tocustomer = omsUtil.getCustomer(toshopid); //调入客户
        if (tocustomer != null && tocustomer != null) {
            //仓库
            String storewhnumber = fromcustomer.getStorewhnumber();
            String storewhname = fromcustomer.getStorewhname();
            String tostorewhnumber = tocustomer.getStorewhnumber();
            String tostorewhname = tocustomer.getStorewhname();

            //成本中心
            String costcenternumber = fromcustomer.getCostcenternumber();
            String costcentername = fromcustomer.getCostcentername();
            String toCostcenternumber = tocustomer.getCostcenternumber();
            String toCostcentername = tocustomer.getCostcentername();

            //调出仓
            omsTransferbill.setFacilitycode(storewhnumber);
            omsTransferbill.setFacilityname(storewhname);
            //调入仓
            omsTransferbill.setTofacilitycode(tostorewhnumber);
            omsTransferbill.setTofacilityname(tostorewhname);
            //调出成本中心
            omsTransferbill.setCostcenterentercode(toCostcenternumber);
            omsTransferbill.setCostcenterentername(toCostcentername);


            //调入成本中心
            omsTransferbill.setCostcenteroutcode(costcenternumber);
            omsTransferbill.setCostcenteroutname(costcentername);
            //组织
            //获取仓库对象
            BdWarehouse fromWarehouse = omsUtil.getBdWarehouse(storewhnumber);
            BdWarehouse toWarehouse = omsUtil.getBdWarehouse(tostorewhnumber);
            if (fromWarehouse != null && toWarehouse != null) {
                String fromstorageorgnumber = fromWarehouse.getStorageorgnumber();
                String fromstorageorgname = fromWarehouse.getStorageorgname();
                String tostorageorgnumber = toWarehouse.getStorageorgnumber();
                String tostorageorgname = toWarehouse.getStorageorgname();

//                omsTransferbill.setInventoryorganizationentercode(fromstorageorgnumber);
//                omsTransferbill.setInventoryorganizationentername(fromstorageorgname);

                omsTransferbill.setInventoryorganizationentercode(tostorageorgnumber);
                omsTransferbill.setInventoryorganizationentername(tostorageorgname);
                omsTransferbill.setInventoryorganizationoutcode(fromstorageorgnumber);
                omsTransferbill.setInventoryorganizationoutname(fromstorageorgname);
            }
        }

        for (OmsTransferbillentry omsTransferbillentry : omsTransferbillentryList) {
            String skucode = omsTransferbillentry.getSkucode();
            BdMaterial material = omsUtil.getMaterial(skucode);
            String materialname = material.getMaterialname();
            String baseunitnumber = material.getBaseunitnumber();
            String baseunitname = material.getBaseunitname();
            omsTransferbillentry.setSkuname(materialname);
            omsTransferbillentry.setBaseunit(baseunitname);
            omsTransferbillentry.setUnit(baseunitnumber);

        }


        //组织


        return omsTransferbill;
    }
    @Override
    public OmsTransferbill getTransferBillByWdt(OmsTransferbill omsTransferbill) {
        String facilitycode = omsTransferbill.getFacilitycode();//调出仓库编码
        String tofacilitycode = omsTransferbill.getTofacilitycode();//调入仓库编码
        List<OmsTransferbillentry> omsTransferbillentryList = omsTransferbill.getOmsTransferbillentryList();

        BdWdtwarehouseconfig bdWdtWarehouse = omsUtil.getBdWdtWarehouse(facilitycode);//调出电商仓库
        BdWdtwarehouseconfig tobdWdtWarehouse = omsUtil.getBdWdtWarehouse(tofacilitycode);//调入电商仓库
        if (bdWdtWarehouse != null) {
            //成本中心
            String costcenternumber = bdWdtWarehouse.getCostcenternumber();
            String costcentername = bdWdtWarehouse.getCostcentername();
//            OmsOrgunit omsOrgunit = omsUtil.getOmsOrgunit(costcenternumber);
//            String costcentername = omsOrgunit.getOrgname();
            //仓库
            BdWarehouse bdWarehouse = omsUtil.getBdWarehouse(bdWdtWarehouse.getWarenumber());//调出仓库
            if (bdWarehouse != null) {
                String fromstorageorgnumber = bdWarehouse.getStorageorgnumber();
                String fromstorageorgname = bdWarehouse.getStorageorgname();

                String storewhnumber = bdWarehouse.getWarehousenumber();
                String storewhname = bdWarehouse.getWarehousename();

                //调出仓
                omsTransferbill.setFacilitycode(storewhnumber);
                omsTransferbill.setFacilityname(storewhname);

                omsTransferbill.setInventoryorganizationoutcode(fromstorageorgnumber);
                omsTransferbill.setInventoryorganizationoutname(fromstorageorgname);
                //调出成本中心
                omsTransferbill.setCostcenteroutcode(costcenternumber);
                omsTransferbill.setCostcenteroutname(costcentername);
            }
        }
        if (tobdWdtWarehouse != null) {
            //成本中心
            String costcenternumber = tobdWdtWarehouse.getCostcenternumber();
            String costcentername = bdWdtWarehouse.getCostcentername();
            //仓库
            BdWarehouse bdWarehouse = omsUtil.getBdWarehouse(tobdWdtWarehouse.getWarenumber());//调入仓库
            if (bdWarehouse != null) {
                String fromstorageorgnumber = bdWarehouse.getStorageorgnumber();
                String fromstorageorgname = bdWarehouse.getStorageorgname();

                String storewhnumber = bdWarehouse.getWarehousenumber();
                String storewhname = bdWarehouse.getWarehousename();

                //调入仓
                omsTransferbill.setTofacilitycode(storewhnumber);
                omsTransferbill.setTofacilityname(storewhname);

                omsTransferbill.setInventoryorganizationentercode(fromstorageorgnumber);
                omsTransferbill.setInventoryorganizationentername(fromstorageorgname);
                //调入成本中心
                omsTransferbill.setCostcenterentercode(costcenternumber);
                omsTransferbill.setCostcenterentername(costcentername);
            }
        }
        if(omsTransferbill.getFacilitycode().equals(omsTransferbill.getTofacilitycode())){
            omsTransferbill.setIscreatebill(-2L);
        }

        for (OmsTransferbillentry omsTransferbillentry : omsTransferbillentryList) {
            String skucode = omsTransferbillentry.getSkucode();
            BdMaterial material = omsUtil.getMaterial(skucode);
            if (material!=null) {
                String materialname = material.getMaterialname();
                String baseunitnumber = material.getBaseunitnumber();
                String baseunitname = material.getBaseunitname();
                omsTransferbillentry.setSkuname(materialname);
                omsTransferbillentry.setBaseunit(baseunitname);
                omsTransferbillentry.setUnit(baseunitnumber);
            }
        }
        return omsTransferbill;
    }

    /**
     * 校验调拨单
     *
     * @param omsTransferbill
     * @return
     */
    @Override
    public StringBuffer checkBill(OmsTransferbill omsTransferbill) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("Over");

        String srcsys = omsTransferbill.getsrcsys();

        String facilitycode = omsTransferbill.getFacilitycode(); //调出仓库编码
        String inventoryorganizationoutcode = omsTransferbill.getInventoryorganizationoutcode();//调出组织编码

        String saleswarehousecode = omsTransferbill.getTofacilitycode(); //调入仓库编码

        String inventoryorganizationentercode = omsTransferbill.getInventoryorganizationentercode();//调出库存组织编码
        Date tradecreatedat = omsTransferbill.getTradecreatedat(); //业务日期

        if (StringUtils.isEmpty(srcsys)) {
            buffer.append("来源系统srcsys为空;");
        } else {
            //校验单据类型为oms的
            if ("oms".equals(srcsys)) {
                if (StringUtils.isEmpty(facilitycode)) {
                    buffer.append("调出仓库facilitycode为空;");
                }else {
                    if (StringUtils.isNotEmpty(inventoryorganizationoutcode)){
                        BdWarehouse bdWarehouse = new BdWarehouse();
                        bdWarehouse.setWarehousenumber(facilitycode);
                        List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
                        if (StringUtils.isEmpty(bdWarehouses)){
                            buffer.append("调出仓库：" + facilitycode + " 不存在;");
                        }else {
                            bdWarehouse = bdWarehouses.get(0);
                            String storageorgnumber = bdWarehouse.getStorageorgnumber();
                            if (!storageorgnumber.equals(inventoryorganizationoutcode)){
                                buffer.append("调出仓库的库存组织：" + storageorgnumber + " 不等于调出组织：" + inventoryorganizationoutcode).append(';');
                            }
                        }
                    }
                }

                if (StringUtils.isEmpty(inventoryorganizationoutcode)) {
                    buffer.append("调出组织编码inventoryorganizationoutcode为空;");
                }
                if (StringUtils.isNull(tradecreatedat)){
                    buffer.append("业务日期tradecreatedat为空;");
                }else {
                    judgeTransferDate(omsTransferbill);
                }

                if (StringUtils.isEmpty(saleswarehousecode)) {
                    buffer.append("调入仓库saleswarehousecode为空;");
                }else {
                    if (StringUtils.isNotEmpty(inventoryorganizationentercode)){
                        BdWarehouse bdWarehouse = new BdWarehouse();
                        bdWarehouse.setWarehousenumber(saleswarehousecode);
                        List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
                        if (StringUtils.isEmpty(bdWarehouses)){
                            buffer.append("调入仓库：" + saleswarehousecode + " 不存在;");
                        }else {
                            bdWarehouse = bdWarehouses.get(0);
                            String storageorgnumber = bdWarehouse.getStorageorgnumber();
                            if (!storageorgnumber.equals(inventoryorganizationentercode)){
                                buffer.append("调入仓库的库存组织：" + storageorgnumber + " 不等于调入组织：" + inventoryorganizationentercode).append(';');
                            }
                        }
                    }
                }

                if (StringUtils.isEmpty(inventoryorganizationentercode)) {
                    buffer.append("调出库存组织inventoryorganizationentercode为空;");
                }
            }
            if ("wdt".equals(srcsys)){
                if (StringUtils.isEmpty(facilitycode)) {
                    buffer.append("调出仓库facilitycode为空;");
                }else {
                    BdWdtwarehouseconfig bdWdtWarehouse = omsUtil.getBdWdtWarehouse(facilitycode);//调出电商仓库
                    if (bdWdtWarehouse==null){
                        buffer.append("电商仓库：" + facilitycode + " 不存在;");
                    }else {
                        BdWarehouse bdWarehouse = new BdWarehouse();
                        String warenumber = bdWdtWarehouse.getWarenumber();
                        if (StringUtils.isEmpty(warenumber)) {
                            buffer.append("电商仓库:"+facilitycode+"的配置表仓库为空;");
                        }
//                        String costcenternumber = bdWdtWarehouse.getCostcenternumber();
//                        if (StringUtils.isEmpty(costcenternumber)) {
//                            buffer.append("电商仓库:"+facilitycode+"的配置表成本中心为空;");
//                        }else{
//                            OmsOrgunit omsOrgunit = omsUtil.getOmsOrgunit(costcenternumber);
//                            if (omsOrgunit==null){
//                                buffer.append("电商仓库:"+facilitycode+"的配置表成本中心:"+costcenternumber+"不存在;");
//                            }
//                        }
                        bdWarehouse.setWarehousenumber(warenumber);
                        List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
                        if (bdWarehouses==null||bdWarehouses.size()==0){
                            buffer.append("电商仓库:"+facilitycode+"的配置表-调出仓库：" + bdWdtWarehouse.getWarenumber() + " 不存在;");
                        }else{
                            bdWarehouse = bdWarehouses.get(0);
                            if (StringUtils.isEmpty(bdWarehouse.getStorageorgnumber())) {
                                buffer.append("电商仓库:"+facilitycode+"的配置表-调出仓库-库存组织编码为空;");
                            }
                        }
                    }
                }
                if (StringUtils.isNull(tradecreatedat)){
                    buffer.append("业务日期tradecreatedat为空;");
                }else {
                    judgeTransferDate(omsTransferbill);
                }
                if (StringUtils.isEmpty(saleswarehousecode)) {
                    buffer.append("调入仓库saleswarehousecode为空;");
                }else {
                    BdWdtwarehouseconfig bdWdtWarehouse = omsUtil.getBdWdtWarehouse(saleswarehousecode);//调出电商仓库
                    if (bdWdtWarehouse==null){
                        buffer.append("电商仓库：" + saleswarehousecode + " 不存在;");
                    }else {
                        BdWarehouse bdWarehouse = new BdWarehouse();
                        String warenumber = bdWdtWarehouse.getWarenumber();
                        if (StringUtils.isEmpty(warenumber)) {
                            buffer.append("电商仓库:"+facilitycode+"的配置表仓库为空;");
                        }
//                        String costcenternumber = bdWdtWarehouse.getCostcenternumber();
//                        if (StringUtils.isEmpty(costcenternumber)) {
//                            buffer.append("电商仓库:"+facilitycode+"的配置表成本中心为空;");
//                        }else{
//                            OmsOrgunit omsOrgunit = omsUtil.getOmsOrgunit(costcenternumber);
//                            if (omsOrgunit==null){
//                                buffer.append("电商仓库:"+facilitycode+"的配置表成本中心:"+costcenternumber+"不存在;");
//                            }
//                        }
                        bdWarehouse.setWarehousenumber(warenumber);
                        List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
                        if (bdWarehouses==null||bdWarehouses.size()==0){
                            buffer.append("调入仓库：" + bdWdtWarehouse.getWarenumber() + " 不存在;");
                        }else{
                            bdWarehouse = bdWarehouses.get(0);
                            if (StringUtils.isEmpty(bdWarehouse.getStorageorgnumber())) {
                                buffer.append("电商仓库:"+facilitycode+"的配置表-调出仓库-库存组织编码inventoryorganizationoutcode为空;");
                            }
                        }
                    }
                }
            }
        }

        List<OmsTransferbillentry> omsTransferbillentryList = omsTransferbill.getOmsTransferbillentryList();
        if (omsTransferbillentryList==null||omsTransferbillentryList.size()==0){
            buffer.append("分录为空;");
            return buffer;
        }else{
            for (int i = 0; i < omsTransferbillentryList.size(); i++) {
                OmsTransferbillentry omsTransferbillentry = omsTransferbillentryList.get(i);
                String skucode = omsTransferbillentry.getSkucode();
                BdMaterial material = omsUtil.getMaterial(skucode);
                if (material==null) {
                    buffer.append("物料:"+skucode+"不存在;");
                }
            }
        }

        for (OmsTransferbillentry omsTransferbillentry : omsTransferbillentryList) {
            String skucode = omsTransferbillentry.getSkucode();
            BigDecimal qty = omsTransferbillentry.getQty();

            if (StringUtils.isEmpty(skucode)) {
                buffer.append("物料skucode为空;");
            }
            if (qty != null) {
                if (qty.compareTo(BigDecimal.ZERO) == 0) {
                    buffer.append("请求数量为0;");
                }
            } else {
                buffer.append("请求数量qty为空;");
            }

        }

        return buffer;
    }

    private void judgeTransferDate(OmsTransferbill omsTransferbill) {
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM月");
        Date tradecreatedat = omsTransferbill.getTradecreatedat();
        Calendar transferCalendar = Calendar.getInstance();
        transferCalendar.setTime(tradecreatedat);
        //获取月份，判断是否属于当前月份
        int TransferMonth = transferCalendar.get(Calendar.MONTH);
        Calendar nowCalendar = Calendar.getInstance();
        Date nowDate = new Date();
        nowCalendar.setTime(nowDate);
        int nowMonth = nowCalendar.get(Calendar.MONTH);
        if (nowMonth != TransferMonth){
            omsTransferbill.setIscreatebill(-3L);
            StringBuffer tempStringBuffer = new StringBuffer();
            tempStringBuffer.append("当前单据的业务日期为：" + dateFormat1.format(tradecreatedat) + " 不等于当前的月份：" + dateFormat2.format(nowDate));
            String errMsg = tempStringBuffer.toString();
            omsTransferbill.setReason(errMsg);
        }
    }

    /**
     * 校验收货确认
     *
     * @param omsReceiptbill
     * @return
     */
    @Override
    public StringBuffer checkBill(OmsReceiptbill omsReceiptbill) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("Over");
        String srcsys = omsReceiptbill.getSrcsys(); //来源系统
        String sourceplatformcode = omsReceiptbill.getSourceplatformcode();//来源上游平台
        String sourceordercode = omsReceiptbill.getSourceordercode(); //来源上游单号

        String customercode = omsReceiptbill.getCustomercode(); //客户编码
        String invoicecode = omsReceiptbill.getInvoicecode();  //销售组织编码

        String saleswarehousecode = omsReceiptbill.getSaleswarehousecode(); //销售组织仓库编码
        String inventoryorganizationcode = omsReceiptbill.getInventoryorganizationcode(); //库存组织编码
        String facilitycode = omsReceiptbill.getFacilitycode(); //发货仓库编码
        Date receiptdate = omsReceiptbill.getReceiptdate(); //发货日期

        if (StringUtils.isEmpty(srcsys)) {
            buffer.append("来源系统srcsys为空;");
        }

        if (StringUtils.isEmpty(sourceplatformcode)) {
            buffer.append("来源上游平台saleswarehousecode为空;");
        }

        if (StringUtils.isEmpty(customercode)) {
            buffer.append("客户编码customercode为空;");
        } else {
            //校验内部客户的收货仓库和销售组织之间的关系
            checkReceiveFacility(omsReceiptbill, buffer, customercode, invoicecode);
        }

        if (StringUtils.isEmpty(sourceordercode)) {
            buffer.append("来源上游单号sourceordercode为空;");
        }

        if (StringUtils.isEmpty(invoicecode)) {
            buffer.append("销售组织编码invoicecode为空;");
        }


        if (StringUtils.isEmpty(saleswarehousecode)) {
            buffer.append("销售组织仓库编码saleswarehousecode为空;");
        }

        if (StringUtils.isEmpty(inventoryorganizationcode)) {
            buffer.append("库存组织编码inventoryorganizationcode为空;");
        }


        if (StringUtils.isEmpty(facilitycode)) {
            buffer.append("发货仓库编码facilitycode为空;");
        }else {
            if (StringUtils.isNotEmpty(inventoryorganizationcode)){
                BdWarehouse bdWarehouse = new BdWarehouse();
                bdWarehouse.setWarehousenumber(facilitycode);
                List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
                if (StringUtils.isNotEmpty(bdWarehouses)){
                    bdWarehouse = bdWarehouses.get(0);
                    String storageorgnumber = bdWarehouse.getStorageorgnumber();
                    if (!inventoryorganizationcode.equals(storageorgnumber)){
                        buffer.append("发货仓库的库存组织:" + storageorgnumber + "不等于单头的库存组织:" + inventoryorganizationcode).append(';');

                    }
                }else {
                    buffer.append("发货仓库：" + facilitycode + " 不存在;");
                }
            }
        }

        if (receiptdate == null) {
            buffer.append("收货日期receiptdate为空;");
        }else {
            judgeReceiptdate(omsReceiptbill);
        }
        List<OmsReceiptbillentry> omsReceiptbillentryList = omsReceiptbill.getOmsReceiptbillentryList();
        if (StringUtils.isEmpty(omsReceiptbillentryList)) {
            buffer.append("分录为空;");
            return buffer;
        }
        for (OmsReceiptbillentry omsReceiptbillentry : omsReceiptbillentryList) {
            String skucode = omsReceiptbillentry.getSkucode();
            BigDecimal shipqty = omsReceiptbillentry.getReceivedqty();
            BigDecimal baseshipqty = omsReceiptbillentry.getBasereceivedqty();
            if (StringUtils.isEmpty(skucode)) {
                buffer.append("物料skucode为空;");
            }
            if (shipqty != null) {
                if (shipqty.compareTo(BigDecimal.ZERO) == 0) {
                    buffer.append("实发数量为0;");
                }
            } else {
                buffer.append("实发数量shipqty为空;");
            }


            if (baseshipqty != null) {
                if (baseshipqty.compareTo(BigDecimal.ZERO) == 0) {
                    buffer.append("实发数量为0;");
                }
            } else {
                buffer.append("基本实发数量baseshipqty为空;");
            }

        }

        return buffer;
    }

    /**
     * 判断收获确认单的收货日期是否符合当前月份
     * @param omsReceiptbill
     */
    private void judgeReceiptdate(OmsReceiptbill omsReceiptbill) {
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM月");
        Date receiptdate = omsReceiptbill.getReceiptdate();
        Calendar receiptCalendar = Calendar.getInstance();
        receiptCalendar.setTime(receiptdate);
        //获取月份，判断是否属于当前月份
        int receipMonth = receiptCalendar.get(Calendar.MONTH);
        Calendar nowCalendar = Calendar.getInstance();
        Date nowDate = new Date();
        nowCalendar.setTime(nowDate);
        int nowMonth = nowCalendar.get(Calendar.MONTH);
        if (nowMonth != receipMonth){
            omsReceiptbill.setIscreatebill(-3L);
            omsReceiptbill.setIscreateoutbill(-3L);
            StringBuffer tempStringBuffer = new StringBuffer();
            tempStringBuffer.append("当前单据的收货日期为：" + dateFormat1.format(receiptdate) + " 不等于当前的月份：" + dateFormat2.format(nowDate));
            String errMsg = tempStringBuffer.toString();
            omsReceiptbill.setReason(errMsg);
            omsReceiptbill.setOutreason(errMsg);
        }
    }

    /**
     * 收货确认校验收货仓库
     * @param omsReceiptbill
     * @param buffer
     * @param customercode
     * @param invoicecode
     */
    private void checkReceiveFacility(OmsReceiptbill omsReceiptbill, StringBuffer buffer, String customercode, String invoicecode) {
        BdCustomer customer = omsUtil.getCustomer(customercode);
        if (StringUtils.isNull(customer)) {
            return;
        }
        if (customer.getIsinternal() == 0L && customer.getIscostcenter() == 0L) {
            return;
        }
        String receivefacilitycode = omsReceiptbill.getReceivefacilitycode();
        if (StringUtils.isEmpty(receivefacilitycode)) {
            buffer.append("收货仓库编码receivefacilitycode为空;");
            return;
        }
        if (StringUtils.isEmpty(invoicecode)) {
            return;
        }
        BdWarehouse bdWarehouse = new BdWarehouse();
        bdWarehouse.setWarehousenumber(receivefacilitycode);
        List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
        if (StringUtils.isEmpty(bdWarehouses)) {
            buffer.append("仓库:" + receivefacilitycode + " 不存在;");
            return;
        }
        bdWarehouse = bdWarehouses.get(0);
        //获取仓库的库存组织
        String storageorgnumber = bdWarehouse.getStorageorgnumber();
        if (!invoicecode.equals(storageorgnumber)) {
            buffer.append("收货仓库的库存组织:" + storageorgnumber + " 不等于单据头的销售组织:" + invoicecode).append(';');
        }
    }



    /**
     * 校验销售退货
     * @param omsSalereturnbill
     * @return
     */
    @Override
    public StringBuffer checkBill(OmsSalereturnbill omsSalereturnbill) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("Over");
        String srcsys = omsSalereturnbill.getSrcsys(); //来源系统


        String customercode = omsSalereturnbill.getCustomercode(); //客户编码
        String invoicecode = omsSalereturnbill.getInvoicecode();  //开票组织


        Date tradecreatedat = omsSalereturnbill.getTradecreatedat(); //下单日期
        Date closeAt = omsSalereturnbill.getCloseat();

        if (StringUtils.isEmpty(srcsys)) {
            buffer.append("来源系统srcsys为空;");
        }


        if (StringUtils.isEmpty(customercode)) {
            buffer.append("售后单位编码customercode为空;");
        }

        if (StringUtils.isEmpty(invoicecode)) {
            buffer.append("开票组织编码invoicecode为空;");
        }


        if (tradecreatedat == null) {
            buffer.append("下单日期tradecreatedat为空;");

        }
        //实际入库时间校验
        if (StringUtils.isNull(closeAt)) {
            buffer.append("实际入库时间closeat为空;");
        }else {
            judgeSaleReturnDate(omsSalereturnbill);
        }

        List<OmsSalereturnbillentry> omsSalereturnbillentryList = omsSalereturnbill.getOmsSalereturnbillentryList();
        if (StringUtils.isEmpty(omsSalereturnbillentryList)){
            buffer.append("分录为空;");
            return buffer;
        }
        for (int i = 0; i < omsSalereturnbillentryList.size(); i++) {
            OmsSalereturnbillentry omsSalereturnbillentry = omsSalereturnbillentryList.get(i);
            String skucode = omsSalereturnbillentry.getSkucode();
            BigDecimal qty = omsSalereturnbillentry.getQty();
            String returnwarehousecode = omsSalereturnbillentry.getReturnwarehousecode();
            if (StringUtils.isEmpty(skucode)) {
                buffer.append("[第" + (i + 1) + "条分录" + "物料skucode为空;");
            }
            if (qty != null) {
                if (qty.compareTo(BigDecimal.ZERO) == 0) {
                    buffer.append("[第" + (i + 1) + "条分录" + "售后数量为0;");
                }
            } else {
                buffer.append("[第" + (i + 1) + "条分录" + "售后数量qty为空;");
            }


            if (StringUtils.isEmpty(returnwarehousecode)) {

                buffer.append("[第" + (i + 1) + "条分录" + "退入仓库returnwarehousecode为空;");
            }else {
                judgeSalereturnEntryNonqty(buffer, i, omsSalereturnbillentry, returnwarehousecode);
            }
        }

        return buffer;
    }

    /**
     * 校验销售退货日期
     * @param omsSalereturnbill
     */
    private void judgeSaleReturnDate(OmsSalereturnbill omsSalereturnbill) {
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM月");
        Date closeAt = omsSalereturnbill.getCloseat();
        Calendar saleReturnCalendar = Calendar.getInstance();
        saleReturnCalendar.setTime(closeAt);
        //获取月份，判断是否属于当前月份
        int saleReturnMonth = saleReturnCalendar.get(Calendar.MONTH);
        Calendar nowCalendar = Calendar.getInstance();
        Date nowDate = new Date();
        nowCalendar.setTime(nowDate);
        int nowMonth = nowCalendar.get(Calendar.MONTH);
        if (nowMonth != saleReturnMonth){
            omsSalereturnbill.setIscreatebill(-3L);
            omsSalereturnbill.setIscreateoutbill(-3L);
            StringBuffer tempStringBuffer = new StringBuffer();
            tempStringBuffer.append("当前单据的实际入库日期为：" + dateFormat1.format(closeAt) + " 不等于当前的月份：" + dateFormat2.format(nowDate));
            String errMsg = tempStringBuffer.toString();
            omsSalereturnbill.setReason(errMsg);
            omsSalereturnbill.setOutreason(errMsg);
        }
    }

    /**
     * 校验销售退货分录无实物数量相关
     * @param buffer
     * @param i
     * @param omsSalereturnbillentry
     * @param returnwarehousecode
     */
    private void judgeSalereturnEntryNonqty(StringBuffer buffer, int i, OmsSalereturnbillentry omsSalereturnbillentry, String returnwarehousecode) {
        //无实物退货数量大于0，则虚拟仓库编码不能为空，且虚拟退货仓库的库存组织必须等于退入仓库的库存组织。
        //仓库承担无实物数量
        BigDecimal warehousenoneqty = omsSalereturnbillentry.getWarehousenoneqty();
        if (StringUtils.isNull(warehousenoneqty) || warehousenoneqty.compareTo(BigDecimal.ZERO) < 1) {
            return;
        }
            String virtualreturnwarehousecode = omsSalereturnbillentry.getVirtualreturnwarehousecode();
        if (StringUtils.isEmpty(virtualreturnwarehousecode)) {
            buffer.append("[第" + (i + 1) + "条分录" + "无实物退货数量大于0，虚拟退货仓库编码不能为空！");
            return;
        }
        //退入仓库
        BdWarehouse bdWarehouse1 = new BdWarehouse();
        //虚拟退货仓库
        BdWarehouse bdWarehouse2 = new BdWarehouse();
        bdWarehouse1.setWarehousenumber(returnwarehousecode);
        List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse1);
        if (StringUtils.isEmpty(bdWarehouses)){
            buffer.append("[第" + (i + 1) + "条分录");
            buffer.append("校验退入仓库和虚拟退货仓库的库存组织是否相等时：");
            buffer.append("仓库：" + returnwarehousecode + " 不存在]");
            return;
        }
        bdWarehouse1 = bdWarehouses.get(0);
        bdWarehouse2.setWarehousenumber(virtualreturnwarehousecode);
        List<BdWarehouse> bdWarehouses1 = warehouseService.selectBdWarehouseList(bdWarehouse2);
        if (StringUtils.isEmpty(bdWarehouses1)){
            buffer.append("[第" + (i + 1) + "条分录");
            buffer.append("校验退入仓库和虚拟退货仓库的库存组织是否相等时：");
            buffer.append("仓库：" + virtualreturnwarehousecode + " 不存在]");
            return;
        }
        bdWarehouse2 = bdWarehouses1.get(0);
        //校验退入仓库的库存组织是否等于虚拟退货仓库的库存组织

        String storageorgnumber1 = bdWarehouse1.getStorageorgnumber();
        String storageorgnumber2 = bdWarehouse2.getStorageorgnumber();
        if (StringUtils.isEmpty(storageorgnumber1) || StringUtils.isEmpty(storageorgnumber2)){
            buffer.append("[第" + (i + 1) + "条分录");
            buffer.append("校验退入仓库和虚拟退货仓库的库存组织是否相等时：");
            buffer.append("仓库：" + returnwarehousecode + " 或是仓库：" + virtualreturnwarehousecode + " 的库存组织为空]");
            return;
        }
        if (!storageorgnumber1.equals(storageorgnumber2)){
            buffer.append("[第" + (i + 1) + "条分录");
            buffer.append("退入仓库: " + returnwarehousecode + " 和虚拟退货仓库：" + virtualreturnwarehousecode + " 的库存组织不相等！]");
        }
    }


    /**
     * 校验发货确认
     *
     * @param omsDeliverbill
     * @return
     */
    @Override
    public StringBuffer checkBill(OmsDeliverbill omsDeliverbill) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("Over");
        String srcsys = omsDeliverbill.getSrcsys(); //来源系统
        String sourceplatformcode = omsDeliverbill.getSourceplatformcode();//来源上游平台
        String invoicecode = omsDeliverbill.getInvoicecode();  //销售组织编码

        String saleswarehousecode = omsDeliverbill.getSaleswarehousecode(); //销售组织仓库编码
        String inventoryorganizationcode = omsDeliverbill.getInventoryorganizationcode(); //库存组织编码
        String facilitycode = omsDeliverbill.getFacilitycode(); //发货仓库编码
        String customercode = omsDeliverbill.getCustomercode(); //客户编码
        Date deliverydate = omsDeliverbill.getDeliverydate(); //发货日期

        if (StringUtils.isEmpty(srcsys)) {
            buffer.append("来源系统srcsys为空;");
        }

        if (StringUtils.isEmpty(customercode)) {
            buffer.append("客户customercode为空;");
        }

        if (StringUtils.isEmpty(sourceplatformcode)) {
            buffer.append("来源上游平台saleswarehousecode为空;");
        }

        if (StringUtils.isEmpty(invoicecode)) {
            buffer.append("销售组织编码invoicecode为空;");
        }


        if (StringUtils.isEmpty(saleswarehousecode)) {
            buffer.append("销售组织仓库编码saleswarehousecode为空;");
        }

        if (StringUtils.isEmpty(inventoryorganizationcode)) {
            buffer.append("库存组织编码inventoryorganizationcode为空;");
        }
        if (StringUtils.isNull(deliverydate)){
            buffer.append("发货日期deliverydate为空;");
        }else {
            judgeDeliverydate(omsDeliverbill);
        }

        if (StringUtils.isEmpty(facilitycode)) {
            buffer.append("发货仓库编码facilitycode为空;");
        }else {
            if (StringUtils.isNotEmpty(inventoryorganizationcode)){
                BdWarehouse bdWarehouse = new BdWarehouse();
                bdWarehouse.setWarehousenumber(facilitycode);
                List<BdWarehouse> bdWarehouses = warehouseService.selectBdWarehouseList(bdWarehouse);
                if (StringUtils.isEmpty(bdWarehouses)){
                    buffer.append("仓库：" + facilitycode + " 不存在;");
                }else {
                    bdWarehouse = bdWarehouses.get(0);
                    String storageorgnumber = bdWarehouse.getStorageorgnumber();
                    if (!inventoryorganizationcode.equals(storageorgnumber)){
                        buffer.append("发货仓的库存组织：" + storageorgnumber + " 不等于单据头的库存组织：" + inventoryorganizationcode).append(';');
                    }
                }
            }
        }
        List<OmsDeliverbillentry> omsDeliverbillentryList = omsDeliverbill.getOmsDeliverbillentryList();
        if (StringUtils.isEmpty(omsDeliverbillentryList)){
            buffer.append("分录为空;");
            return buffer;
        }
        for (OmsDeliverbillentry omsDeliverbillentry : omsDeliverbillentryList) {
            String skucode = omsDeliverbillentry.getSkucode();
            BigDecimal shipqty = omsDeliverbillentry.getShipqty();
            BigDecimal baseshipqty = omsDeliverbillentry.getBaseshipqty();
            if (StringUtils.isEmpty(skucode)) {
                buffer.append("物料skucode为空;");
            }
            if (shipqty != null) {
                if (shipqty.compareTo(BigDecimal.ZERO) == 0) {
                    buffer.append("实发数量为0;");
                }
            } else {
                buffer.append("实发数量shipqty为空;");
            }


            if (baseshipqty != null) {
                if (baseshipqty.compareTo(BigDecimal.ZERO) == 0) {
                    buffer.append("基本实发数量为0;");
                }
            } else {
                buffer.append("基本实发数量baseshipqty为空;");
            }

        }

        return buffer;
    }

    @Override
    public StringBuffer calculateReturnbill(OmsSalereturnbill omsSalereturnbill) {

        StringBuffer buffer = new StringBuffer();
        List<OmsSalereturnbillentry> omsSalereturnbillentryList = omsSalereturnbill.getOmsSalereturnbillentryList();
        for (OmsSalereturnbillentry omsSalereturnbillentry : omsSalereturnbillentryList) {
            BigDecimal taxprice = omsSalereturnbillentry.getTaxprice(); //含税单价
            BigDecimal taxamount = omsSalereturnbillentry.getTaxamount(); //含税总金额
            BigDecimal qty = omsSalereturnbillentry.getQty();

            if(taxprice==null){
                buffer.append("[含税单价为空;]");
            }
            if(taxamount==null){
                buffer.append("[含税总金额为空;]");
            }
            if(qty==null){
                buffer.append("[售后数量为空;]");
            }
            Long isgift = omsSalereturnbillentry.getIsgift();

            String skucode = omsSalereturnbillentry.getSkucode();
            BdMaterial bdMaterial = bdMaterialService.selectBdMaterialByNumber(skucode);
            if(StringUtils.isEmpty(skucode)){
                buffer.append("[未找到物料:"+skucode+"的基础信息；]");
            }
            BigDecimal taxrate = bdMaterial.getTaxrate();
            if(taxrate==null){
                buffer.append("[未找到物料:"+skucode+"的税率信息；]");
            }
            if(isgift==0l&&(qty.compareTo(BigDecimal.ZERO)==1)&&(taxprice.compareTo(BigDecimal.ZERO)==0)){//不是赠品，数量大于0，含税单价==0
                buffer.append("[物料:"+skucode+"不为赠品，数量不为0的情况下，含税单价不可为空；]");
            }
//            1.taxrate 税率 ：取结算中心物料主档上的税率
//            2.notaxprice 不含税单价：通过含税单价taxprice / （1+税率taxrate/100），保留6位小数
//            3.notaxamount 不含税总金额 ：通过notaxprice 不含税单价 * qty 售后数量 ，保留2位小数
//            4.tax 税额 ：taxamount 含税总金额 - notaxamount 不含税总金额

            if(buffer.length()==0){
                BigDecimal rate = taxrate.divide(new BigDecimal("100"),6,4).add(BigDecimal.ONE);
                BigDecimal notaxprice = taxprice.divide(rate, 6, 4);

                BigDecimal notaxamount = notaxprice.multiply(qty).setScale(2, 4);

                BigDecimal tax = taxamount.subtract(notaxamount); //税额
                omsSalereturnbillentry.setTaxrate(taxrate);
                omsSalereturnbillentry.setNotaxprice(notaxprice);
                omsSalereturnbillentry.setNotaxamount(notaxamount);
                omsSalereturnbillentry.setTax(tax);
                omsSalereturnbillentry.setSystaxprice(taxprice); //系统含税单价 = 含税单价
            }

        }
        return buffer;
    }

    /**
     * 校验发货确认的业务日期，是否符合当前月份
     * @param omsDeliverbill
     */
    private void judgeDeliverydate(OmsDeliverbill omsDeliverbill) {
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM月");
        Date deliverydate = omsDeliverbill.getDeliverydate();
        Calendar deliveryCalendar = Calendar.getInstance();
        deliveryCalendar.setTime(deliverydate);
        //获取月份，判断是否属于当前月份
        int receipMonth = deliveryCalendar.get(Calendar.MONTH);
        Calendar nowCalendar = Calendar.getInstance();
        Date nowDate = new Date();
        nowCalendar.setTime(nowDate);
        int nowMonth = nowCalendar.get(Calendar.MONTH);
        if (nowMonth != receipMonth){
            omsDeliverbill.setIscreatebill(-3L);
            StringBuffer tempStringBuffer = new StringBuffer();
            tempStringBuffer.append("当前单据的发货日期为：" + dateFormat1.format(deliverydate) + " 不等于当前的月份：" + dateFormat2.format(nowDate));
            String errMsg = tempStringBuffer.toString();
            omsDeliverbill.setReason(errMsg);
        }
    }
}
